package com.eh.base;

import com.eh.exception.ExceptionData;
import com.eh.exception.ServiceWarningException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * Created by David Li on 2015/12/2.
 */
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @ExceptionHandler(ServiceWarningException.class)
    @ResponseBody
    public ResponseWrapper serviceWarningExceptionHandler(ServiceWarningException exception) {
        ResponseWrapper responseWrapper = new ResponseWrapper(ResponseWrapper.Status.PRECONDITION_FAILD);
        if (exception.getCode() != null) {
            ExceptionData exceptionData = new ExceptionData("Some thing Error");
            responseWrapper.setData(exceptionData);
            logger.warn(exceptionData.toString(), exception);
        } else {
            logger.warn(exception.getLocalizedMessage(), exception);
        }
        return responseWrapper;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseWrapper exceptionHandler(Exception exception) {
        logger.error(exception.getLocalizedMessage(), exception);
        ResponseWrapper dataWrapper = new ResponseWrapper(ResponseWrapper.Status.BAD_REQUEST, getExceptionStackTrace(exception));
        return dataWrapper;
    }

    private String getExceptionStackTrace(Exception e) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(byteArrayOutputStream, true);
        try {
            e.printStackTrace(printStream);
            return byteArrayOutputStream.toString();
        } finally {
            printStream.close();
        }
    }

}
